<style lang="less">
@import "./style.less";
</style>
<template>
	<div class="user">
		<div class="op-header">
			<el-button @click="add" class="add" size="small" type="info">
				<i class="el-icon-circle-plus icon-right"/>创建考试
			</el-button>
			<div class="search">
				<el-cascader
					:clearable="true"
					:options="enableOptions"
					:props="cascaderProps"
					class="enable-select"
					placeholder="启用状态"
					v-model="enableValue"
				/>
				<el-input
					class="search-input"
					placeholder="请输入查询关键字"
					prefix-icon="el-icon-search"
					size="small"
					v-model="searchInput"
				/>
				<el-button @click="search" class="search-button" size="small" type="primary">
					<i class="el-icon-search icon-right"/>查询
				</el-button>
			</div>
		</div>
		<table-ex
			:columns="columns"
			:on-operation="onClickOperation"
			:on-option="onClickOption"
			:on-page-change="onPageChange"
			:options="options"
			:rows="examList.content"
			:total="examList.total"
		/>
		<dialog-ex
			:form="form"
			:init="currentExam"
			:mode="dialogModal"
			:popup-focus="popupFocus"
			:popup-value="releaseObjc"
			:remote-method="onQueryChange"
			:search-data="paperList.content"
			:title="this.dialogModal === 'add' ? '创建考试' : '编辑考试'"
			v-if="dialogModal"
		/>
		<multistage
			:data="leftdata"
			:default-props="multistageProps"
			:init-data="traineeIds"
			:modal-cancel="multistageCancel"
			:modal-confirm="multistageConfirm"
			:table-columns="multistageColumns"
			:table-rows="traineeList"
			:tree-node-click="(row, path) => multistageNodeClick(row, path)"
			row-key="userId"
			title="选择学员"
			v-if="multistageModal"
		/>
	</div>
</template>

<script>
import { mapActions, mapGetters, mapMutations } from "vuex";
import { Message } from "element-ui";
import { Base64 } from "js-base64";
import pageConfig from "./config";
import api from "@/api";

import tableEx from "@/components/table/tableEx";
import dialogEx from "@/components/dialog/dialogEx";
import multistage from "@/components/custom/multistage";

export default {
  name: "user",
  components: {
    "table-ex": tableEx,
    "dialog-ex": dialogEx,
    multistage: multistage
  },
  data() {
    return {
      searchInput: "",
      table: "",
      tableFlag: false,
      enableValue: [],
      departmentValue: "",
      leftdata: "",
      paperId: null,
      multistageModal: false,
      columns: pageConfig.columns,
      traineeIds: [],
      options: pageConfig.options,
      releaseObjc: "",
      learnList: "",
      multistageRow: {},
      enableOptions: pageConfig.enableOptions,
      multistageProps: pageConfig.multistageProps,
      multistageColumns: pageConfig.multistageColumns,
      cascaderProps: {
        value: "id",
        label: "name",
        children: "subClasses"
      },
      dialogModal: "",
      currentExam: {},
      form: {
        items: pageConfig.addExamFormItems,
        default: { enabled: true },
        actions: {
          cancel: () => {
            this.dialogModal = "";
          },
          confirm: (data, mode) => {
            this.paperId = data.paperId;
            if (mode === "add") {
              this.addExam({
                data,
                cb: res => {
                  this.addPaperRelation(res);
                  this.addTraineeRelation(res);
                }
              });
            }
            if (mode === "edit") {
              this.addPaperRelation(data);
              this.addTraineeRelation(data);
              this.updateExam(data);
            }
            this.dialogModal = "";
          }
        }
      }
    };
  },

  computed: {
    ...mapGetters(["examList", "paperList", "deparList", "traineeList"])
  },
  created() {},
  mounted() {
    this.loadInitData();
  },
  methods: {
    ...mapActions([
      "getexamlist",
      "removeone_exam",
      "addExam",
      "updateExam",
      "GetPaperList",
      "getDeparList",
      "getTraineeList"
    ]),
    ...mapMutations([
      "setsexamList",
      "SETEXAMPAGE",
      "setTrainList",
      "SETTRAINEELIST"
    ]),

    add() {
      this.releaseObjc = "";
	  this.traineeIds = [];
      this.$store.commit("SETTRAINEELIST", []);
      this.dialogModal = "add";
    },

    addPaperRelation(objc) {
      if (this.paperId) {
        let data = {
          id: objc.id,
          action: "replace",
          lIds: [this.paperId]
        };
        api.addPaperRelation(data, {
          success: res => {}
        });
      }
    },

    addTraineeRelation(objc) {
      if (this.traineeIds.length) {
        let data = {
          action: "replace",
          id: objc.id,
          lIds: this.traineeIds
        };
        api.addTraineeRelation(data, {
          success: res => {}
        });
      }
    },

    loadInitData() {
      this.getexamlist();
      this.GetPaperList();
      this.getDeparList();
    },

    search() {
      const filter = {
        name: this.searchInput,
        enabled: !!this.enableValue ? this.enableValue[0] : null
      };
      this.SETEXAMPAGE({
        number: 1,
        pages: 0,
        filter
      });
      this.getexamlist();
    },

    onQueryChange(query) {
      let data = {
        size: 10,
        number: 0,
        total: 0,
        pages: 0,
        filter: {
          name: query
        }
      };
      this.GetPaperList(data);
    },

    batchOption() {},

    onClickOption(option, rows) {
      const prop = option;
      switch (prop) {
        case "batchdelete": {
          let id = row.map(item => {
            return item.id;
          });
          this.removeone_exam(id);
          break;
        }
        case "refresh": {
          this.loadInitData();
          break;
        }
        default: {
        }
      }
    },

    onClickOperation(oper, row) {
      let self = this;
      let optstyle = oper.prop;
      let id = row.id;
      const prop = oper.prop;
      switch (prop) {
        case "preview": {
          api.queryOneExam(id, {
            success: exam => {
              if (!exam.examPapers || exam.examPapers.length === 0) {
                Message({
                  center: true,
                  type: "warning",
                  message: "没有配置试卷不能预览"
                });
                return;
              }
              // 改成1:1,虽然Java端是使用关系定义
              api.queryOnePaper(exam.examPapers[0].id, {
                success: paper => {
                  if (
                    paper &&
                    (!paper.businessTemplates ||
                      paper.businessTemplates.length === 0)
                  ) {
                    Message({
                      center: true,
                      type: "warning",
                      message: "没有配置业务不能预览"
                    });
                    return;
                  }
                  self.$router.push({
                    name: "courseBusiness",
                    query: {
                      course: Base64.encode(
                        JSON.stringify({
                          businessId: paper.businessTemplates[0].id,
                          examId: exam.id,
                          examPaperId: paper.id,
                          mode: "exam",
                          action: "preview"
                        })
                      )
                    }
                  });
                  self.$store.commit("course/update", {
                    businessTemplates: paper.businessTemplates
                  });
                }
              });
            }
          });
          break;
        }
        case "delete": {
          this.removeone_exam([id]);
          break;
        }
        case "edit": {
          api.queryOneExam(row.id, {
            success: res => {
              // 改成1:1,虽然Java端是使用关系定义
              let employeNames = [];
              if (res.examPapers && res.examPapers.length) {
                let paperIds = res.examPapers.map(item => {
                  return item.id;
                });
                paperIds && (res["paperId"] = paperIds[0]);
              }
              if (res.employees && res.employees.length) {
                this.traineeIds = res.employees.map(item => {
                  return item.id;
                });
                res.employees.forEach(item => {
                  employeNames.push(item.name);
                });
              }
              this.releaseObjc = `已选${employeNames.length}人`;
              this.currentExam = res;
              this.dialogModal = "edit";
            }
          });
          break;
        }
        default: {
        }
      }
    },
    popupFocus(e) {
      this.leftdata = this.deparList;
	  this.$store.commit('SETTRAINEELIST', [])
      this.multistageModal = true;
    },
    multistageConfirm(results) {
      this.multistageModal = false;
      this.traineeIds = results;
      this.releaseObjc = `已选${this.traineeIds.length}人`;
    },
    multistageNodeClick(row) {
      let rowId = row ? row.id : "";
      const data = {
        size: 10000,
        number: 0,
        total: 0,
        pages: 0,
        filter: {
          enabled: true,
          orgIds: [rowId]
        }
      };
      this.multistageRow = row;
      this.getTraineeList(data);
    },

    multistageCancel(e) {
      this.multistageModal = false;
    },

    onPageChange(number) {
      this.SETEXAMPAGE({ number });
      this.getexamlist();
    }
  }
};
</script>
